package com.frxuexi.demo.news

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.frxuexi.base.entity.RecordEntity
import com.frxuexi.base.mvvm.BaseViewModel
import com.frxuexi.base.net.ApiService
import com.frxuexi.base.net.ApiServiceNews
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject

@HiltViewModel
class NewsViewModel @Inject constructor(val apiService: ApiServiceNews):BaseViewModel() {

    val newsSuccess = MutableStateFlow<List<RecordEntity>>(emptyList())

    fun getNews(page:Int){
        httpRequestNews({apiService.getNews(page)},{
            newsSuccess.value=it.records
        })
    }

    fun getNewsPagingData():Flow<PagingData<RecordEntity>>{
        return Pager(PagingConfig(10), pagingSourceFactory = {NewsDataSource(apiService)}).flow.cachedIn(viewModelScope)
    }
}